package com.feijia.aijingjingus;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.RelativeSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.feijia.aijingjingus.util.PreferencesUtils;
import com.feijia.aijingjingus.view.Dialog;
import com.zjun.progressbar.CircleDotProgressBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.feijia.aijingjingus.GlobalHelper.AD1;
import static com.feijia.aijingjingus.GlobalHelper.AD1List;
import static com.feijia.aijingjingus.GlobalHelper.AD2;
import static com.feijia.aijingjingus.GlobalHelper.AD2List;
import static com.feijia.aijingjingus.GlobalHelper.ADRecord;
import static com.feijia.aijingjingus.GlobalHelper.BatteryValue;
import static com.feijia.aijingjingus.GlobalHelper.BleAddress;
import static com.feijia.aijingjingus.GlobalHelper.BleB;
import static com.feijia.aijingjingus.GlobalHelper.BleBeatsSpan;
import static com.feijia.aijingjingus.GlobalHelper.BleData;
import static com.feijia.aijingjingus.GlobalHelper.BleDisconnCountDown;
import static com.feijia.aijingjingus.GlobalHelper.BleG;
import static com.feijia.aijingjingus.GlobalHelper.BleR;
import static com.feijia.aijingjingus.GlobalHelper.CYConn;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE_SHOW_AD;
import static com.feijia.aijingjingus.GlobalHelper.DEBUG_MODE_SHOW_TOAST_AD;
import static com.feijia.aijingjingus.GlobalHelper.DetectionDatetime;
import static com.feijia.aijingjingus.GlobalHelper.DetectionLocation;
import static com.feijia.aijingjingus.GlobalHelper.DetectionResults;
import static com.feijia.aijingjingus.GlobalHelper.DetectionType;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.Mode;
import static com.feijia.aijingjingus.GlobalHelper.NeedUploadDetection;
import static com.feijia.aijingjingus.GlobalHelper.NeedUploadDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBuffer;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferSize;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferTwo;
import static com.feijia.aijingjingus.GlobalHelper.NewestDetectDataBufferTwoSize;
import static com.feijia.aijingjingus.GlobalHelper.RawDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.Report;
import static com.feijia.aijingjingus.GlobalHelper.SHOW_DYNAMIC_VALUE;
import static com.feijia.aijingjingus.GlobalHelper.ShowAD;
import static com.feijia.aijingjingus.GlobalHelper.ShowLocalDetection;
import static com.feijia.aijingjingus.GlobalHelper.ShowRGB;
import static com.feijia.aijingjingus.GlobalHelper.StartDetecting;
import static com.feijia.aijingjingus.GlobalHelper.TempThreshold;
import static com.feijia.aijingjingus.GlobalHelper.TemperatureDetect;
import static com.feijia.aijingjingus.GlobalHelper.TestPCB;

import static com.feijia.aijingjingus.GlobalHelper.UploadRawDetectionData;
import static com.feijia.aijingjingus.GlobalHelper.isBleConnectingOrConnected;
import static com.feijia.aijingjingus.GlobalHelper.isNetOut;
import static com.feijia.aijingjingus.GlobalHelper.isPingSuccess;
import static com.feijia.aijingjingus.GlobalHelper.tip;
import static com.feijia.aijingjingus.GlobalHelper.BleHandler;
import static com.feijia.aijingjingus.GlobalHelper.handler;

import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class DetectingActivity extends AppCompatActivity {
    Dialog dialog;
    Activity activity = this;
    CircleDotProgressBar cdProgressBar;
    LineChartView chartView;
    LineChartData chartData;
    //Random random = new Random();
    List<PointValue> pointValues = new ArrayList<>();
    List<PointValue> pointValues2 = new ArrayList<>();
    List<PointValue> pointValues3 = new ArrayList<>();
    List<PointValue> pointValuesR = new ArrayList<>();
    List<PointValue> pointValuesG = new ArrayList<>();
    List<PointValue> pointValuesB = new ArrayList<>();
    List<PointValue> pointValuesAD1 = new ArrayList<>();
    List<PointValue> pointValuesAD2 = new ArrayList<>();
    ArrayList<AxisValue> axisValuesX = new ArrayList<>();
    Axis axisX = new Axis();
    ArrayList<AxisValue> axisValuesY = new ArrayList<>();
    Axis axisY = new Axis().setHasLines(true).setTextSize(10);
    List<Line> lines = new ArrayList<>();
    float progress = 1;
    Viewport v;
    //Handler handler;
    private  boolean FIRST_HINT=true;
    private boolean IS_LOW_ELECTRICITY=false;
    int TimeCount = 0;
    private static final int TimeCountMax = 70;
    private static final int ChartW = 26;
    private static final int GetDataTimeSpan = BleBeatsSpan;
    private static final float Step = 1.6f;
    private int DataCount = 0;
    private double DataSum = 0;
    private TextView tvDetectValue, tvIU;
    RelativeLayout rlDetectingBleOut, ShowResultRelativeLayout;
    ImageButton imBattery;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    RelativeLayout rlDe;
    FrameLayout flPSview;
    OptionsPickerView pvNetOut;
    Context context = this;
    final int AxisXMAX = 30;
    int thresholdOfUnreacted,thresholdOfNoIndication;double  thresholdOfNegative,thresholdOfpositive;
    String hcgDropSign,hcgWrongSign,hcgNegativeSign,hcgPositiveSign;
    float hcgDropSignRelativeSize,hcgWrongSignRelativeSize,hcgNegativeSignRelativeSize,hcgPositiveSignRelativeSize;

    private Handler diaHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                //这里增加对case 1和2的处理
                case 1:
//                  检测完成
                    dialog=new Dialog(DetectingActivity.this,Constants.SCAN_OK);
                    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    dialog.show();
                    break;
//                  电量不足
                case 2:
                    dialog=new Dialog(DetectingActivity.this,Constants.BATTERY);
                    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    dialog.show();
                    break;

            }
        }
    };

    final Runnable showDoneRL = new Runnable() {
        @Override
        public void run() {
            //更新界面
            RelativeLayout rlDone = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);

            rlDone.setVisibility(View.VISIBLE);
            //boolean result =mBleService.writeCharacteristic(txCharacteristic,("CMD_OFF".getBytes()));
            //System.out.println("Ble 写入结果:" + result+",写入:"+ "CMD_OFF");

            //完成检测
            RelativeLayout that = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);
            that.setVisibility(View.GONE);

           diaHandler.sendEmptyMessage(1);
           ShowLocalDetection = true;
//          startActivity(new Intent("DetectionResultActivity"));
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        ADRecord.clear();
        StartDetecting = true;
        setContentView(R.layout.activity_detecting);
//        tvDetectValue = (TextView) findViewById(R.id.DetectValue);

        cdProgressBar=(CircleDotProgressBar)findViewById(R.id.cd_progressbar);
        tvIU = (TextView) findViewById(R.id.tvIU);
        rlDetectingBleOut = (RelativeLayout) findViewById(R.id.rlDetectingBleOut);
        ShowResultRelativeLayout = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);
//        imBattery = (ImageButton) findViewById(R.id.imBattery);
        rlDe = rlDetectingBleOut;
//        flPSview = (FrameLayout) findViewById(R.id.flPSview);
        TemperatureDetect=false;


        //      性别男时修改UI背景色
//        if(PreferencesUtils.getString(getApplicationContext(),PreferencesUtils.PREFERENCE_NAME).equals("男")){
//            RelativeLayout rl_top=(RelativeLayout)findViewById(R.id.relativeLayout);
//            rl_top.setBackground(getDrawable(R.drawable.top_bar_with_shadow_two));
////          cdProgressBar.setDotBgColor(Color.parseColor("#009FCC"));
//            cdProgressBar.setDotColor(Color.parseColor("#9ec0d2"));
//            cdProgressBar.setUnitTextColor(Color.parseColor("#9ec0d2"));
//            cdProgressBar.setPercentTextColor(Color.parseColor("#9ec0d2"));
//            }

        Thread getMode = new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject outMode = GlobalHelper.PostData(new JSONObject(), "http://120.77.255.57/ting/getMode.php");
                try {
                    GlobalHelper.Mode = outMode.getInt("Result");
                    TempThreshold = outMode.getInt("TempThreshold");
                    thresholdOfUnreacted = outMode.getInt("thresholdOfUnreacted");
                    thresholdOfNoIndication = outMode.getInt("thresholdOfNoIndication");
                    thresholdOfNegative = outMode.getDouble("thresholdOfNegative");
                    thresholdOfpositive = outMode.getDouble("thresholdOfpositive");
                    hcgDropSign = outMode.getString("hcgDropSign");
                    hcgWrongSign = outMode.getString("hcgWrongSign");
                    hcgNegativeSign = outMode.getString("hcgNegativeSign");
                    hcgPositiveSign = outMode.getString("hcgPositiveSign");
                    hcgDropSignRelativeSize = (float)outMode.getDouble("hcgDropSignRelativeSize");
                    hcgWrongSignRelativeSize = (float)outMode.getDouble("hcgWrongSignRelativeSize");
                    hcgNegativeSignRelativeSize = (float)outMode.getDouble("hcgNegativeSignRelativeSize");
                    hcgPositiveSignRelativeSize = (float)outMode.getDouble("hcgPositiveSignRelativeSize");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                System.out.println("MODE:" + GlobalHelper.Mode);
            }
        });
        getMode.start();

        pvNetOut = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_net_out_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvNetOut.returnData();
                                pvNetOut.dismiss();
                                Intent intent = new Intent("controlCenterActivity");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //pvNetOut.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        TestPCB = true;
        //旧蓝牙模块用
        /*
        BleHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch_view (msg.what){
                    case 0:

                        //Bundle bundle = msg.getData();
                        //System.out.println("BleHandler通知返回:"+Arrays.toString(bundle.getIntArray("BleData")));

                        break;
                    default:break;
                }
            }
        };
        */
//        chartView = (LineChartView) findViewById(R.id.lineChart);

        for (int i = 0; i < TimeCountMax; i += 5) {
            int x = i;
            int y = 10;
            //pointValues.add(new PointValue(x, y));
            //pointValues3.add(new PointValue(x, y));
            axisValuesX.add(new AxisValue(x).setValue(x).setLabel(""));
        }

        //axisValuesY.add(new AxisValue(0).setValue(10));
        pointValues2.add(new PointValue(0, 0));
        pointValues2.add(new PointValue(TimeCountMax, 3000));
        axisX.setValues(axisValuesX);
        //axisX.setHasLines(true);
        //axisX.setTextColor(getResources().getColor(R.color.zero));
        axisY.setValues(axisValuesY);
        axisY.setHasLines(true);
        Line line = new Line(pointValues);
        line.setHasLabels(true);
        line.setCubic(true);
        line.setCubic(true);
        line.setHasPoints(false);
        lines.add(line);
        Line line3 = new Line(pointValues3);
        line3.setHasLabels(true);
        line3.setCubic(true);
        line3.setCubic(true);
        line3.setHasPoints(false);
        lines.add(line3);
        Line line2 = new Line(pointValues2);
        line2.setColor(ContextCompat.getColor(context, R.color.zero));
        lines.add(line2);
        Line lineR = new Line(pointValuesR);
        Line lineG = new Line(pointValuesG);
        Line lineB = new Line(pointValuesB);
        Line lineAD1 = new Line(pointValuesAD1);
        Line lineAD2 = new Line(pointValuesAD2);
        lines.add(lineR);
        lines.add(lineG);
        lines.add(lineB);
        lines.add(lineAD1);
        lines.add(lineAD2);
//        chartData = new LineChartData(lines);
        //chartData.setBaseValue(10);
//        chartData.setAxisXBottom(axisX);
        /*
        if(!DEBUG_MODE)
            axisY.setTextColor(ContextCompat.getColor(context, R.color.zero));

        chartData.setAxisYLeft(axisY);
        */
//        if (DEBUG_MODE)
//            chartData.setAxisYLeft(axisY);
//        chartData.setValueLabelBackgroundEnabled(false);
//        chartData.setValueLabelTextSize(10);
//        chartView.setLineChartData(chartData);
        //chartView.setScrollEnabled(false);
//        v = new Viewport(chartView.getMaximumViewport());
//        v.left = 0;
//        v.right = ChartW;
//        chartView.setCurrentViewport(v);
//        final WaveProgressView waveProgressbar = (WaveProgressView) findViewById(R.id.waveProgressbar);
//        waveProgressbar.setWaveColor("#FF5F78");


        //Intent serviceIntent = new Intent(this, BleService.class);
        //bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);


        Thread writeData = new Thread(new Runnable() {
            @Override
            public void run() {
                /*String Msg = "";
                if(CYConn)
                    Msg="CMD_ON";
                else {
                    Msg = "AT:BLE-ONAA";
                    TimeCount=-5;
                }
                if(txCharacteristic==null)
                    System.out.println("Ble txCharacteristic=null");
                boolean result =mBleService.writeCharacteristic(txCharacteristic,(Msg.getBytes()));
                System.out.println("Ble 写入结果:" + result+",写入:"+ Msg);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                result =mBleService.writeCharacteristic(txCharacteristic,(Msg.getBytes()));
                System.out.println("Ble 写入结果:" + result+",写入:"+ Msg);
                */
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                BleHandler.sendEmptyMessage(0);
            }
        });


        Thread updatePoint = new Thread(new Runnable() {
            /**
             *
             */
            @Override
            public void run() {
                int timeSpan = 50;
                int count = 0;
                final RelativeLayout rlResult = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);
//                final TextView tvBatteryValue = (TextView) findViewById(R.id.tvBatteryValue);

                while (progress < 100 && rlResult.getVisibility() != View.VISIBLE && isBleConnectingOrConnected/* || TestPCB*/) {

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (BatteryValue == 999) {
//                                tvBatteryValue.setText("");
                            } else {
                                int v = (int) ((BatteryValue - 215) / 0.15);
                                if(v<0)
                                    v*=-1;
                                if (v <= 0)
                                    v = 1;
                                if (v > 100)
                                    v = 100;
//                                tvBatteryValue.setText("" + v + "%");

                                if (v<=35){
                                    IS_LOW_ELECTRICITY=true;
                                }

//                                if (v <= 66 && v > 33) {
//                                    imBattery.setBackground(getDrawable(R.drawable.power75));
//                                } else if (v <= 33) {
//                                    imBattery.setBackground(getDrawable(R.drawable.power25));
//                                } else if (v > 66) {
//                                    imBattery.setBackground(getDrawable(R.drawable.power100));
//                                }
                            }
                        }
                    });


                    BleHandler.sendEmptyMessage(3);
                    /*
                    try {

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(200);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (rlDe != null) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (!isBleConnectingOrConnected&&rlResult.getVisibility() != View.VISIBLE)
                                                rlDe.setVisibility(View.VISIBLE);
                                        }
                                    });
                                }
                            }
                        }).start();

                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
*/
                    try {
                        Thread.sleep(timeSpan);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    //System.out.println("Ble newest "+NewestDetectDataBuffer[0]+"  "+NewestDetectDataBuffer[1]+"  "+NewestDetectDataBuffer[2]);

                    if (progress < 100 && count % (1000 / timeSpan) == 0) {
                        progress += Step;
                        if (BleDisconnCountDown + 1 <= 0) {
                            //BleHandler.sendEmptyMessage(1);
                        }
                        BleDisconnCountDown--;
                    }
                    if (progress >= 100 && !DEBUG_MODE && rlDetectingBleOut.getVisibility() == View.GONE) {
                        isNetOut = isPingSuccess(3, "120.77.255.57") != 0;
                        System.out.println("Net S D in sending:" + (!isNetOut));
                        if (!isNetOut) {
                            JSONObject root = new JSONObject();
                            try {
                                if (!GUserNum.isEmpty())
                                    root.put("UserNo", Long.parseLong(GUserNum) /*Long.parseLong(GUserNum)*/);
                                else {
                                    root.put("UserNo", new Random().nextInt() * -1);
                                    NeedUploadDetection = true;
                                }
                                //DetectionLocation = "San Diago";
                                root.put("DetectionDate", sdf.format(new Date()));
                                root.put("DetectionLocation", DetectionLocation);
                                root.put("DetectionEquipmentType", BleAddress);
                                root.put("Report", "sample");
                                root.put("RawDetectionData", UploadRawDetectionData);
                                for (int i = 0; i < ADRecord.size()/2 ; i++) {
                                    root.put("AD1"+i, ADRecord.get(2*i));
                                    root.put("AD2"+i, ADRecord.get(2*i+1));
                                }
                                float sum = 0;

                                for (int i = 0; i < NewestDetectDataBufferSize; i++) {
                                    sum += NewestDetectDataBuffer[i];
                                }
                                if (GlobalHelper.Mode == 1)
                                    root.put("Remarks", (NewestDetectDataBuffer[0] + NewestDetectDataBuffer[1] + NewestDetectDataBuffer[2]) / NewestDetectDataBufferSize);
                                else {
                                    //for (int i = 0; i < NewestDetectDataBufferSize; i++) {
                                    //    sum += NewestDetectDataBuffer[i];
                                    //}
                                    //System.out.println("Ble post" + ((NewestDetectDataBuffer[0] + NewestDetectDataBuffer[1] + NewestDetectDataBuffer[2]) / NewestDetectDataBufferSize) + " sum:" + sum + " size:" + NewestDetectDataBufferSize);
                                    root.put("Remarks", (NewestDetectDataBuffer[0]+NewestDetectDataBuffer[1]+NewestDetectDataBuffer[2])/NewestDetectDataBufferSize);
                                    //root.put("Remarks", AD1);
                                    //for (int i = 0; i < NewestDetectDataBufferTwoSize; i++) {
                                    //    sum += NewestDetectDataBufferTwo[i];
                                    //}
                                    root.put("DetectionResults", (NewestDetectDataBufferTwo[0]+NewestDetectDataBufferTwo[1]+NewestDetectDataBufferTwo[2])/NewestDetectDataBufferTwoSize);
                                    //root.put("DetectionResults", AD2);
                                }
                                System.out.println("Ble Post:" + Mode);
                                System.out.println("Ble Post:" + "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                                System.out.println("Ble Post:" + root);
                                JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                                System.out.println("Ble Post: back:" + out);
                                if (out.getInt("OperateResult") == 0) {
                                    out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                                }
                                if (out.getInt("OperateResult") == 0) {
                                    out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                                }
                                if (out.getInt("OperateResult") == 0) {
                                    out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                                }
                                NeedUploadDetectionData = root;
                                System.out.println("Ble Post:" + out);
                                Report = out.getString("Report");
                                tip = out.getString("tip");
                                //DetectionLocation=out.getString("DetectionLocation");

                                DetectionResults = out.getString("DetectionResults");
                                RawDetectionData = out.getDouble("RawDetectionData") + "";


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
//                            handler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    new ParticleSystem(activity, ((int) progress) / 5, R.drawable.psd, 3000, R.id.flPSparent)
//                                            //.addModifier(new AlphaModifier(0,255,0,2000))
//                                            .setFadeOut(1000)
//                                            .addModifier(new ScaleModifier(0, 0.6f, 200, 1250))
//                                            .setSpeedRange(0.1f, 0.2f)
//                                            .oneShot(flPSview, 5);
//                                }
//                            });
                            new Thread(new Runnable() {
                                @Override
                                public void run() {

                                    try {
                                        Thread.sleep(50);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

//                                    waveProgressbar.setText("#FFFFFF",24);
//                                    waveProgressbar.setCurrent(100, getString(R.string.MakingDetection));
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

//                                    waveProgressbar.setText("#FFFFFF",24);
//                                    waveProgressbar.setCurrent(100, getString(R.string.MakingDetection) + ".");
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

//                                    waveProgressbar.setText("#FFFFFF",24);
//                                    waveProgressbar.setCurrent(100, getString(R.string.MakingDetection) + "..");
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
//
//                                    waveProgressbar.setText("#FFFFFF",24);
//                                    waveProgressbar.setCurrent(100, getString(R.string.MakingDetection) + "...");
                                    try {
                                        Thread.sleep(500);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    BleHandler.sendEmptyMessage(1);
                                    handler.post(showDoneRL);
                                }
                            }).start();

                            progress = 102;
                            //boolean result =mBleService.writeCharacteristic(txCharacteristic,"CMD_OFF".getBytes());
                            //System.out.println("Ble 写入结果:" + result);

                        /*
                        if (mBleService!=null)
                            mBleService.close();
                            */
                        } else {
                            BleHandler.sendEmptyMessage(1);

                            pvNetOut.setPicker(new ArrayList<>());//添加数据
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    pvNetOut.show();
                                }
                            });

                        }
                    }
                    AbsoluteSizeSpan span = new AbsoluteSizeSpan(24, true);
                    SpannableString s = new SpannableString((int) progress + "%");
                    s.setSpan(span, 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

//                    waveProgressbar.setText("#FFFFFF",70);
                    if (progress < 100)
                        cdProgressBar.setProgress((int) progress);

//                        waveProgressbar.setCurrent((int) progress, s.toString());

/*
                    for (Iterator<PointValue> ipv = pointValues.iterator(); ipv.hasNext(); ) {
                        PointValue pv = ipv.next();
                        pv.set(pv.getX() - 1 * (timeSpan / 1000.0f), pv.getY());
                    }
                    if (count % (1000 / timeSpan) == 0) {
                        int x = 20;
                        float y = 20 * random.nextFloat();
                        pointValues.add(new PointValue(x, y));
                        pointValues.remove(0);
                    }
*/
/*
                    for (Iterator<PointValue> ipv = pointValues.iterator(); ipv.hasNext(); ) {
                        PointValue pv = ipv.next();
                        pv.set(pv.getX() - 1 * (timeSpan / 1000.0f), pv.getY());
                        pv.setLabel(pv.getY()+"");
                    }
                    for (Iterator<PointValue> ipv = pointValues3.iterator(); ipv.hasNext(); ) {
                        PointValue pv = ipv.next();
                        pv.set(pv.getX() - 1 * (timeSpan / 1000.0f), pv.getY());
                        pv.setLabel(pv.getY()+"");
                    }
                    */
                    if (count % (GetDataTimeSpan * 1000 / timeSpan) == 0) {
                        /*
                        for (int i=0; i<pointValues.size()-1;i++ ) {
                            PointValue pv = pointValues.get(i);
                            PointValue pvn = pointValues.get(i + 1);
                            pv.set(pvn.getX(), pvn.getY());
                            pv.setLabel(pv.getY()+"");
                        }
                        for (int i=0; i<pointValues3.size()-1;i++ ) {
                            PointValue pv = pointValues3.get(i);
                            PointValue pvn = pointValues3.get(i + 1);
                            pv.set(pvn.getX(), pvn.getY());
                            pv.setLabel(pv.getY()+"");
                        }
                        */
                        //int x = AxisXMAX;
                        //float y = 20 * random.nextFloat();
                        if (CYConn && !ShowAD) {
                            /*//老版
                            int y1 = BleData[0];
                            int y2 = BleData[1];
                            if (y1 > y2) {
                                pointValues.add(new PointValue().set(TimeCount, y1).setLabel(y1 + "      "));
                                pointValues3.add(new PointValue().set(TimeCount, y2).setLabel("      " + y2));
                            } else if (y1 < y2) {
                                pointValues.add(new PointValue().set(TimeCount, y1).setLabel("      " + y1));
                                pointValues3.add(new PointValue().set(TimeCount, y2).setLabel(y2 + "      "));
                            } else {
                                pointValues.add(new PointValue().set(TimeCount, y1).setLabel(y1 + ""));
                                pointValues3.add(new PointValue().set(TimeCount, y2).setLabel(y2 + ""));
                            }
                            DataCount += 2;
                            DataSum += y1 + y2;

                            Line line = new Line(pointValues);
                            line.setCubic(false);
                            line.setHasLabels(true);
                            line.setHasPoints(true);
                            line.setPointRadius(3);
                            line.setColor(ContextCompat.getColor(context, R.color.ChartRed));
                            Line line3 = new Line(pointValues3);
                            line3.setHasLabels(true);
                            line3.setCubic(false);
                            line3.setHasPoints(true);
                            line3.setPointRadius(3);
                            line3.setColor(ContextCompat.getColor(context, R.color.ChartBlue));
                            lines.set(0,line);
                            lines.set(2,line3);
                            */
                            if (DEBUG_MODE) {
                                pointValuesR.add(new PointValue().set(TimeCount, BleR).setLabel(BleR + ""));
                                pointValuesG.add(new PointValue().set(TimeCount, BleG).setLabel(BleG + ""));
                                pointValuesB.add(new PointValue().set(TimeCount, BleB).setLabel(BleB + ""));
                            } else {
                                pointValuesR.add(new PointValue().set(TimeCount, BleR));
                                pointValuesG.add(new PointValue().set(TimeCount, BleG));
                                pointValuesB.add(new PointValue().set(TimeCount, BleB));
                            }
                            DataCount += 3;
                            DataSum += BleR + BleG + BleB;
                            Line lineR = new Line(pointValuesR);
                            Line lineG = new Line(pointValuesG);
                            Line lineB = new Line(pointValuesB);
                            lineR.setCubic(false);
                            lineR.setHasLabels(true);
                            lineR.setHasPoints(true);
                            lineR.setPointRadius(3);
                            lineR.setColor(ContextCompat.getColor(context, R.color.ChartRed));
                            lineG.setCubic(false);
                            lineG.setHasLabels(true);
                            lineG.setHasPoints(true);
                            lineG.setPointRadius(3);
                            lineG.setColor(ContextCompat.getColor(context, R.color.ChartGreen));
                            lineB.setCubic(false);
                            lineB.setHasLabels(true);
                            lineB.setHasPoints(true);
                            lineB.setPointRadius(3);
                            lineB.setColor(ContextCompat.getColor(context, R.color.ChartBlue));
                            lines.set(3, lineR);
                            lines.set(4, lineG);
                            lines.set(5, lineB);
                        }
                        Line line2 = new Line(pointValues2);
                        line2.setColor(ContextCompat.getColor(context, R.color.zero));
                        lines.set(1, line2);
                        if (ShowRGB) {
                            if (DEBUG_MODE) {
                                pointValuesR.add(new PointValue().set(TimeCount, BleR).setLabel(BleR + ""));
                                pointValuesG.add(new PointValue().set(TimeCount, BleG).setLabel(BleG + ""));
                                pointValuesB.add(new PointValue().set(TimeCount, BleB).setLabel(BleB + ""));
                            } else {
                                pointValuesR.add(new PointValue().set(TimeCount, BleR));
                                pointValuesG.add(new PointValue().set(TimeCount, BleG));
                                pointValuesB.add(new PointValue().set(TimeCount, BleB));
                            }
                            Line lineR = new Line(pointValuesR);
                            Line lineG = new Line(pointValuesG);
                            Line lineB = new Line(pointValuesB);
                            DataCount += 3;
                            DataSum += BleR + BleG + BleB;
                            lineR.setCubic(false);
                            lineR.setHasLabels(true);
                            lineR.setHasPoints(true);
                            lineR.setPointRadius(3);
                            lineR.setColor(ContextCompat.getColor(context, R.color.ChartRed));
                            lineG.setCubic(false);
                            lineG.setHasLabels(true);
                            lineG.setHasPoints(true);
                            lineG.setPointRadius(3);
                            lineG.setColor(ContextCompat.getColor(context, R.color.ChartGreen));
                            lineB.setCubic(false);
                            lineB.setHasLabels(true);
                            lineB.setHasPoints(true);
                            lineB.setPointRadius(3);
                            lineB.setColor(ContextCompat.getColor(context, R.color.ChartBlue));
                            lines.set(3, lineR);
                            lines.set(4, lineG);
                            lines.set(5, lineB);
                        }
                        if (ShowAD) {
                            if (DEBUG_MODE) {
                                pointValuesAD1.add(new PointValue().set(TimeCount - 5, AD1).setLabel(AD1 + ""));
                                pointValuesAD2.add(new PointValue().set(TimeCount - 5, AD2).setLabel(AD2 + ""));
                            } else {
                                pointValuesAD1.add(new PointValue().set(TimeCount - 5, AD1));
                                pointValuesAD2.add(new PointValue().set(TimeCount - 5, AD2));
                            }
                            Line lineAD1 = new Line(pointValuesAD1);
                            Line lineAD2 = new Line(pointValuesAD2);
                            DataCount += 2;
                            DataSum += AD1 + AD2;
                            lineAD1.setCubic(true);
                            if (DEBUG_MODE)
                                lineAD1.setHasLabels(true);
                            lineAD1.setHasPoints(true);
                            lineAD1.setPointRadius(3);
                            lineAD1.setColor(ContextCompat.getColor(context, R.color.ChartRed));
                            lineAD2.setCubic(true);
                            if (DEBUG_MODE)
                                lineAD2.setHasLabels(true);
                            lineAD2.setHasPoints(true);
                            lineAD2.setPointRadius(3);
                            lineAD2.setColor(ContextCompat.getColor(context, R.color.ChartBlue));
                            lines.set(6, lineAD1);
                            lines.set(7, lineAD2);
                        }
                        //lines =  new ArrayList<Line>(){{add(line); add(line2);}};
//                        chartData = new LineChartData(lines);
                        //chartData.setBaseValue(10);
//                        chartData.setValueLabelBackgroundEnabled(false);
//                        chartData.setValueLabelTextSize(10);
//                        chartData.setAxisXBottom(axisX);
                        /*
                        if(!DEBUG_MODE)
                            axisY.setTextColor(ContextCompat.getColor(context, R.color.zero));

                        chartData.setAxisYLeft(axisY);
                        */
//                        chartData.setAxisYLeft(axisY);
//                        chartView.setLineChartData(chartData);
                        //if(CYConn&&ShowAD)
//                        v.top = 3000;
//                        if (TimeCount > ChartW) {
//                            v.left = TimeCount - ChartW;
//                            v.right = TimeCount;
//                        }
//                        chartView.setCurrentViewport(v);
                        final String temp;
                        int tempint = 0;
                        if (CYConn && !ShowAD) {
                            /*//老版
                            temp = "<font color='#DF1F93'>" + BleData[0] + "</font><br/>" + "<font color='#2C55D1'>" + BleData[1] + "</font>";
                            tempint = 30;
                            */
                            temp = "<font color='#df1f93'>" + BleR + "    </font>" + "<font color='#9ced65'>" + BleG + "</font><br/>" + "<font color='#2c55d1'>" + BleB + "     </font>" + "<font color='#0'>" + BleData[0] + "</font>";
                            tempint = 20;
                        } else if (ShowRGB) {
                            temp = "<font color='#df1f93'>" + BleR + "</font><br/>" + "<font color='#9ced65'>" + BleG + "</font><br/>" + "<font color='#2c55d1'>" + BleB + "</font>";
                            tempint = 20;
                        } else if (DEBUG_MODE_SHOW_TOAST_AD) {
                            float avgAd1 = 0, avgAd2 = 0;
                            int sumAd1 = 0, sumAd2 = 0;
                            for (int i = 4; i < AD1List.size(); i++) {
                                sumAd1 += AD1List.get(i);
                                sumAd2 += AD2List.get(i);
                            }
                            if (AD1List.size() - 4 > 0) {
                                avgAd1 = (float) sumAd1 / (AD1List.size() - 4);
                                avgAd2 = (float) sumAd2 / (AD1List.size() - 4);
                            }
                            temp = "<font color='#DF1F93'>" + AD1 + "</font><br/>" + "<font color='#2C55D1'>" + AD2 + "</font><br/>" + "<font color='#2c55d1'>" + avgAd1 + "</font><br/>" + "<font color='#2c55d1'>" + avgAd2 + "</font>";
                            tempint = 15;
                        } else {
                            temp = "<font color='#DF1F93'>" + AD1 + "</font><br/>" + "<font color='#2C55D1'>" + AD2 + "</font>";
                            tempint = 30;
                        }
                        final String str = temp;
                        final int fontSize = tempint;
                        if (DEBUG_MODE || DEBUG_MODE_SHOW_AD || DEBUG_MODE_SHOW_TOAST_AD) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //tvDetectValue.setText(Html.fromHtml(str));
                                    //tvDetectValue.setTextSize(fontSize);
                                    String tempRawDetectionData = "";
                                    int tempRawData = AD1;

                                    /*if (tempRawData > TempThreshold)
                                        tempRawDetectionData = "<5";
                                    else
                                        tempRawDetectionData = ">100";
                                    */
                                    int t12dot5min = 1178;
                                    int t12dot5max = 1188;
                                    int t25min = 1168;
                                    int t25max = 1177;
                                    int t50min = 1115;
                                    int t50max = 1125;
                                    int t100min = 1080;
                                    int t100max = 1090;
                                    int t200min = 1048;
                                    int t200max = 1058;

                                    /*
                                    if (tempRawData > 1188)
                                        tempRawDetectionData = "<12.5";
                                    else if(tempRawData >= t12dot5min && tempRawData <= t12dot5max)
                                        tempRawDetectionData = "12.5";
                                    else if(false)
                                        tempRawDetectionData = "12.5~25";
                                    else if(tempRawData >= t25min && tempRawData <= t25max)
                                        tempRawDetectionData = "25";
                                    else if(tempRawData >= t50max+1 && tempRawData <= t25min-1)
                                        tempRawDetectionData = "25~50";
                                    else if(tempRawData >= t50min && tempRawData <= t50max)
                                        tempRawDetectionData = "50";
                                    else if(tempRawData >= t100max+1 && tempRawData <= t50min-1)
                                        tempRawDetectionData = "50~100";
                                    else if(tempRawData >= t100min && tempRawData <= t100max)
                                        tempRawDetectionData = "100";
                                    else if(tempRawData >= t200max+1 && tempRawData <= t100min-1)
                                        tempRawDetectionData = "100~200";
                                    else if(tempRawData >= t200min && tempRawData <= t200max)
                                        tempRawDetectionData = "200";
                                    else if( tempRawData < t200max)
                                        tempRawDetectionData = ">200";
                                    */
                                    /*
                                    if(tempRawData >= 1143 )
                                        tempRawDetectionData = "25";
                                    else if( tempRawData >= 1100&&tempRawData<1143)
                                        tempRawDetectionData = "50";
                                    else if( tempRawData < 1100)
                                        tempRawDetectionData = "100";
                                    else
                                        tempRawDetectionData = "Detecting";
                                        */
                                    /*
                                    if(AD1>=thresholdOfUnreacted || AD2>=thresholdOfUnreacted) {
                                        tempRawDetectionData = hcgDropSign;
                                    }
                                    else if((AD1<thresholdOfUnreacted && AD1>thresholdOfNoIndication) || (AD2<thresholdOfUnreacted && AD2>thresholdOfNoIndication)) {
                                        tempRawDetectionData = hcgWrongSign;
                                    }else if(AD1*1.0/AD2>thresholdOfNegative){
                                        tempRawDetectionData = hcgNegativeSign;
                                    }else {
                                        tempRawDetectionData = hcgPositiveSign;
                                    }*/
                                    if(AD1<thresholdOfpositive)
                                    {
                                        tempRawDetectionData = hcgPositiveSign;
                                    }
                                    else {
                                        tempRawDetectionData = hcgDropSign;
                                    }
                                    if (tempRawData != 0) {
                                        Spannable span = new SpannableString(DetectionType + "\n" + tempRawDetectionData);
                                        if(tempRawDetectionData!=null&&tempRawDetectionData.equals(hcgDropSign)&&hcgDropSignRelativeSize>0)
                                        {
                                            span.setSpan(new RelativeSizeSpan(hcgDropSignRelativeSize), DetectionType.length(), span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        } else if(tempRawDetectionData!=null&&tempRawDetectionData.equals(hcgWrongSign)&&hcgWrongSignRelativeSize>0){
                                            span.setSpan(new RelativeSizeSpan(hcgWrongSignRelativeSize), DetectionType.length(), span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }else if(tempRawDetectionData!=null&&tempRawDetectionData.equals(hcgNegativeSign)&&hcgNegativeSignRelativeSize>0){
                                            span.setSpan(new RelativeSizeSpan(hcgNegativeSignRelativeSize), DetectionType.length(), span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }else if(tempRawDetectionData!=null&&tempRawDetectionData.equals(hcgPositiveSign)&&hcgPositiveSignRelativeSize>0){
                                            span.setSpan(new RelativeSizeSpan(hcgPositiveSignRelativeSize), DetectionType.length(), span.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }else {
                                            span.setSpan(new RelativeSizeSpan(1.f), 0, DetectionType.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        }
                                        //tvIU.setText(span);
//                                        tvDetectValue.setText(span);
                                    } else if (SHOW_DYNAMIC_VALUE && AD1 != 0) {
                                        /*
                                        float avgAd1=0,avgAd2=0;
                                        int sumAd1=0,sumAd2=0;
                                        for (int i = 4;i<AD1List.size();i++)
                                        {
                                            sumAd1+=AD1List.get(i);
                                            sumAd2+=AD2List.get(i);
                                        }
                                        if(AD1List.size()-4>0) {
                                            avgAd1 = (float) sumAd1 / (AD1List.size() - 4);
                                            avgAd2 = (float) sumAd2 / (AD1List.size() - 4);
                                        }
                                        */
                                        float temp1, temp2, temp3, y, x;
                                        float A = 0.87573f;
                                        float B = 0.33096f;
                                        float C = 1530.19145f;
                                        float D = 0.90227f;

                                        y = AD1;
                                        temp1 = A - D;
                                        temp2 = y - D;
                                        temp3 = temp1 / temp2 - 1;
                                        if (temp3 < 0)
                                            temp3 = temp3 * -1;
                                        x = (float) Math.pow(temp3, 1 / B) * C;
                                        Spannable span = new SpannableString(DetectionType + "\n" + tempRawDetectionData);
                                        span.setSpan(new RelativeSizeSpan(1.f), 0, DetectionType.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                                        tvDetectValue.setText(span);
                                    }

                                    //Toast.makeText(context, BleAddress, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        TimeCount += GetDataTimeSpan;
                    }
                    count++;

                    while (IS_LOW_ELECTRICITY && FIRST_HINT){
                        diaHandler.sendEmptyMessage(2);
                        FIRST_HINT=false;
                    }

                }


            }
        });
        updatePoint.start();
        writeData.start();



    }

    public void onClickDetection(View view) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ShowLocalDetection = true;
        Report = "";//"这里是详细报告";
        tip = "";//"多喝热水";
        double RawData = DataSum / DataCount;
        //RawDetectionData = RawData+"";
        /*
        if (RawData>=847&&RawData<849)
            RawDetectionData = "10";
        else if(RawData>=846&&RawData<847)
            RawDetectionData = "10~20";
        else if(RawData>=844&&RawData<846)
            RawDetectionData = "20";
        else if(RawData>=841&&RawData<844)
            RawDetectionData = "20~30";
        else if(RawData>=839&&RawData<841)
            RawDetectionData = "30";
        else if(RawData>=838&&RawData<839)
            RawDetectionData = "30~50";
        else if(RawData>=836&&RawData<838)
            RawDetectionData = "50";
        else if(RawData>=835&&RawData<836)
            RawDetectionData = "50~100";
        else if(RawData>=834&&RawData<835)
            RawDetectionData = "100";
        else if(RawData>=833&&RawData<834)
            RawDetectionData = "100~150";
        else if(RawData>=832&&RawData<833)
            RawDetectionData = "150~200";
        else if(RawData>=830&&RawData<832)
            RawDetectionData = "250";
        else if(RawData>=815&&RawData<818)
            RawDetectionData = "300";
        else if(RawData>=0&&RawData<815)
            RawDetectionData = "300+";
        else if(RawData>=849&&RawData<1024)
            RawDetectionData = "0~10";
            */
        if (RawData > 615 && RawData < 620)
            RawDetectionData = "5~10";
        else if (RawData <= 615)
            RawDetectionData = "10";
        else if (RawData >= 620)
            RawDetectionData = "5";
        DetectionResults = "0";
        DetectionDatetime = df.format(new Date());
        //DetectionLocation = "上海";
        StartDetecting = false;
        startActivity(new Intent("DetectionResultActivity"));
    }

    public void onClickDetectionConfirm(View view) {
        RelativeLayout that = (RelativeLayout) findViewById(R.id.ShowResultRelativeLayout);
        that.setVisibility(View.GONE);
        ShowLocalDetection = true;
        /*
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Report = "";//"这里是详细报告";
        tip = "";//"多喝热水";
        double RawData = DataSum/DataCount;
        RawDetectionData = String.format("%.2f", RawData).toString();
        if (RawData>=847&&RawData<849)
            RawDetectionData = "10";
        else if(RawData>=846&&RawData<847)
            RawDetectionData = "10~20";
        else if(RawData>=844&&RawData<846)
            RawDetectionData = "20";
        else if(RawData>=841&&RawData<844)
            RawDetectionData = "20~30";
        else if(RawData>=839&&RawData<841)
            RawDetectionData = "30";
        else if(RawData>=838&&RawData<839)
            RawDetectionData = "30~50";
        else if(RawData>=836&&RawData<838)
            RawDetectionData = "50";
        else if(RawData>=835&&RawData<836)
            RawDetectionData = "50~100";
        else if(RawData>=834&&RawData<835)
            RawDetectionData = "100";
        else if(RawData>=833&&RawData<834)
            RawDetectionData = "100~150";
        else if(RawData>=832&&RawData<833)
            RawDetectionData = "150~200";
        else if(RawData>=830&&RawData<832)
            RawDetectionData = "250";
        else if(RawData>=815&&RawData<818)
            RawDetectionData = "300";
        else if(RawData>=0&&RawData<815)
            RawDetectionData = "300+";
        else if(RawData>=849&&RawData<1024)
            RawDetectionData = "0~10";
        DetectionResults="0";
        DetectionDatetime = df.format(new Date());
        //DetectionLocation = "上海";
*/
        startActivity(new Intent("DetectionResultActivity"));
    }

    public void onClickBack(View view) {
        StartDetecting = false;

        //BleHandler.sendEmptyMessage(1);


        finish();
        System.out.println("Ble click Back");
        Intent intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        //finish();
    }

    public void onClickUser(View view) {
        StartDetecting = false;
        startActivity(new Intent("ImprovePersonalInformationActivity"));
    }

    public void onClickDetectionHistory(View view) {
        StartDetecting = false;
        startActivity(new Intent("detectionHistoryActivity"));
    }

    public void onClickStopTest(View view) {
        if (DEBUG_MODE) {
            TestPCB = false;
            handler.post(showDoneRL);
            progress = 100;
        }
        //boolean result =mBleService.writeCharacteristic(txCharacteristic,"CMD_OFF".getBytes());
        //System.out.println("Ble 写入结果:" + result);
        //if (mBleService!=null)
        //    mBleService.close();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && StartDetecting && rlDetectingBleOut.getVisibility() == View.GONE && ShowResultRelativeLayout.getVisibility() == View.GONE) {
            findViewById(R.id.EscRelativeLayout).setVisibility(View.VISIBLE);
        }
        return false;
    }

    public void onClickLoginYes(View view) {
        StartDetecting = false;


        BleHandler.sendEmptyMessage(1);
        //Intent intent =new Intent("MainActivity");
        Intent intent = new Intent("controlCenterActivity");
        if (!GUserNum.isEmpty())
            intent = new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        //unbindService(serviceConnection);
        startActivity(intent);
    }

    public void onClickLoginNo(View view) {
        findViewById(R.id.EscRelativeLayout).setVisibility(View.GONE);
    }
}